package fragments;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import ws.JSONManager;
import ws.JsonParsers;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.cachopoid.R;
import com.cachopoid.activity.MainActivity;
import com.cachopoid.utils.CachopoBaseAdapter;
import com.cachopoid.utils.Constantes;
import com.cachopoid.utils.ListaComentariosBaseAdapter;
import com.cachopoid.utils.ListaExpandableCachoposBaseAdapter;
import com.cachopoid.vo.CachopoVO;
import com.cachopoid.vo.ComentarioVO;
import com.cachopoid.vo.EstablecimientoVO;
import com.cachopoid.vo.FotoVO;

public class FragmentDetalleCachopos extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";
    private static CachopoVO cachopoGlobal= new CachopoVO();
    private static EstablecimientoVO establecimientoGlobal= new EstablecimientoVO();
    Typeface font;
    static ListView listComentarios;
    static RelativeLayout pnlDetalleEstb;
    static ProgressBar pbarProgresoComentarios;
    static JSONObject jsonResult = new JSONObject();
    ArrayList<ComentarioVO> listaComentarios= new ArrayList<ComentarioVO>();
    ArrayList<FotoVO> listaFotos= new ArrayList<FotoVO>();
    ImageView gallery = null;
    static Context context = null;
    
    
    
    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static FragmentDetalleCachopos newInstance(int sectionNumber,CachopoVO cachopo,View v,EstablecimientoVO establecimiento) {
    	FragmentDetalleCachopos fragment = new FragmentDetalleCachopos();
        Bundle args = new Bundle();
        establecimientoGlobal=establecimiento;
        cachopoGlobal=cachopo;
        context = v.getContext();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        
        
        
        return fragment;
    }

    public FragmentDetalleCachopos() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    	
        final View rootView = inflater.inflate(R.layout.fragment_detalle_cachopo, container, false);
        final ExpandableListView expendableList = (ExpandableListView) rootView.findViewById(R.id.detalleEstablecimiento);
        listComentarios= (ListView)rootView.findViewById(R.id.listaComentarios);
        pbarProgresoComentarios = (ProgressBar) rootView.findViewById(R.id.pbarProgresoComentarios);
     //   Button btnVotar = (Button) rootView.findViewById(R.id.btnVotar);
        
        font = Typeface.createFromAsset(container.getContext().getAssets(), "fuente_celta.ttf");
      //  btnVotar.setTypeface(font);
        
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(metrics);
        int width = metrics.widthPixels; 
        metrics = new DisplayMetrics();
        width = metrics.widthPixels;

        expendableList.setIndicatorBounds(width - GetDipsFromPixel(50), width - GetDipsFromPixel(10));
        
        
    
        expendableList.setChildIndicatorBounds(width - GetDipsFromPixel(50), width - GetDipsFromPixel(10));
         expendableList.setAdapter(new ListaExpandableCachoposBaseAdapter(context, establecimientoGlobal));
        expendableList.expandGroup(0);
        
        //**********************************
        //Tabs de Puntuacion y Comentarios
        //********************************
        Resources res = getResources();
        
        TabHost tabs=(TabHost)rootView.findViewById(android.R.id.tabhost);
        tabs.setup();
         
        TabHost.TabSpec spec=tabs.newTabSpec("tabPuntua");
        spec.setContent(R.id.tabPuntuacion);
        spec.setIndicator("PUNTUACION",
            res.getDrawable(android.R.drawable.ic_btn_speak_now));
        tabs.addTab(spec);
         
        spec=tabs.newTabSpec("tabComent");
        spec.setContent(R.id.tabComentarios);
        spec.setIndicator("COMENTARIOS",
            res.getDrawable(android.R.drawable.ic_dialog_map));
        tabs.addTab(spec);
         
        tabs.setCurrentTab(0);
        
        tabs.setOnTabChangedListener(new OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
            	
               if(tabId.equals("tabComent")){
            	   //Seteamos el idCachopo al objeto Comentario para filtrarlo y lanzamos el hilo
            	   ComentarioVO comentarioVO = new ComentarioVO();
            	   comentarioVO.setIdCachopo(cachopoGlobal.getIdCachopo());
            	   threadComentarios  threadComent= new threadComentarios(comentarioVO);
            	   threadComent.execute();
               }
            }
        });
        
        
       
        populateDatosCachopoDetalle(cachopoGlobal,rootView);
        
        // Pone el nombre del cachopo en el titulo del action bar
     //   restoreActionBar(cachopoGlobal.getNombre());
        
       
        
       	
//        threadImgCachopoXEstabl  threadImgCachopoXEstabl = new threadImgCachopoXEstabl();
//        threadImgCachopoXEstabl.execute();
        
        
        
     // Galeria
//		gallery = (ImageView) rootView.findViewById(R.id.gallery);
//		ImageView gallery2 = (ImageView) rootView.findViewById(R.id.gallery2);
//		ImageLoader imageLoader =  new  ImageLoader(container.getContext());
//		imageLoader.DisplayImage("http://cachopoid.esy.es/imagenes/cachopos/chalana/cachopoJamonYQueso2.jpg",  gallery);
//		imageLoader.DisplayImage("http://cachopoid.esy.es/imagenes/cachopos/chalana/cachopoLaChalana.jpg",  gallery2);
		//FotoDAO fotoDAO = new FotoDAO(rootView.getContext());
		//listaFotos = fotoDAO.getFotosXEstablecimiento(cachopoGlobal.getIdEstablecimiento());
		//gallery.setAdapter(new ImageAdapter(this.getActivity(),listaFotos));
//		gallery.setOnItemClickListener(new OnItemClickListener() {
//			
//			public void onItemClick(AdapterView parent,View v,int position,long id){
//				Toast.makeText(rootView.getContext(), ""+position,Toast.LENGTH_SHORT).show();
//				switch(position){
//					case 0:
//						//Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//						//code = SELECT_PICTURE;
//						//TODO A�adir foto
//						//startActivityForResult(intent, position);
//						//startActivity(intent);
//						//System.out.println("asd");
//					break;
//				}
//				
//			}
//		});
		
	
		expendableList.setOnGroupClickListener(new OnGroupClickListener() {
	        @Override
	        public boolean onGroupClick(ExpandableListView arg0, View arg1,
	            int groupPosition, long arg3) {

	        	/*TranslateAnimation ta = new TranslateAnimation(0, 0, Animation.RELATIVE_TO_SELF, 180);
                ta.setDuration(1000);
                ta.setFillAfter(true);
				FrameLayout pnlDetalleEstb = (FrameLayout) rootView.findViewById(R.id.panelPrueba);
				pnlDetalleEstb.setAnimation(ta);*/
				
				LayoutInflater l_Inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				
				View convertView = l_Inflater.inflate(R.layout.template_expend_establec, null);
			
				TextView txtDireccionEstab = (TextView) convertView.findViewById(R.id.direccionEstablecimiento);
				txtDireccionEstab.setTypeface(font);
			    txtDireccionEstab.setText(establecimientoGlobal.getDireccion());
			    TextView txtCiudadEstab = (TextView) convertView.findViewById(R.id.ciudadEstablecimiento);
			    txtCiudadEstab.setTypeface(font);
			    txtCiudadEstab.setText(establecimientoGlobal.getCiudad());
			    TextView txtTlfEstab = (TextView) convertView.findViewById(R.id.tlfEstablecimiento);
			    txtTlfEstab.setText(establecimientoGlobal.getTelefono());
			    
	        return false;
	        }
	        });
				
		expendableList.setOnGroupCollapseListener(new OnGroupCollapseListener(){

			@Override
			public void onGroupCollapse(int arg0) {
			/*	TranslateAnimation ta = new TranslateAnimation(0, 0, Animation.RELATIVE_TO_SELF, 0);
                ta.setDuration(1000);
                ta.setFillAfter(true);
				FrameLayout pnlDetalleEstb = (FrameLayout) rootView.findViewById(R.id.panelPrueba);
				pnlDetalleEstb.setAnimation(ta);*/
				
			}

		});
		       
        return rootView;
    }
  
    
    public int GetDipsFromPixel(float pixels){
     // Get the screen's density scale
     final float scale = getResources().getDisplayMetrics().density;
     // Convert the dps to pixels, based on density scale
     return (int) (pixels * scale + 0.5f);
    }
    
    /**
     * Cambia el nombre al titulo del action pasandole el titulo
     */
    public void restoreActionBar(String mTitle) {
        ActionBar actionBar = this.getActivity().getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }
    
    
    
    private void populateDatosCachopoDetalle(CachopoVO cachopoGlobal, View rootView) {
    	TextView txtNombreCachopo = (TextView) rootView.findViewById(R.id.txtNombreCachopo);
        txtNombreCachopo.setText(cachopoGlobal.getNombre());
        
        final RatingBar rtSaborBar = (RatingBar) rootView.findViewById(R.id.saborBar);
        final RatingBar rtTamanioBar = (RatingBar) rootView.findViewById(R.id.tamanioBar);
        final RatingBar rtPrecioBar = (RatingBar) rootView.findViewById(R.id.precioBar);
        final RatingBar rtRebozadoBar = (RatingBar) rootView.findViewById(R.id.rebozadoBar);
        final RatingBar rtRellenoBar = (RatingBar) rootView.findViewById(R.id.rellenoBar);
        final TextView txtSabor = (TextView) rootView.findViewById(R.id.txtSabor);
        final TextView txtTamanio = (TextView) rootView.findViewById(R.id.txtTamanio);
        final TextView txtPrecio = (TextView) rootView.findViewById(R.id.txtPrecio);
        final TextView txtRebozado = (TextView) rootView.findViewById(R.id.txtRebozado);
        final TextView txtRelleno = (TextView) rootView.findViewById(R.id.txtRelleno);
        
        TextView LblTamanio = (TextView) rootView.findViewById(R.id.LblTamanio);
        TextView LblPrecio = (TextView) rootView.findViewById(R.id.LblPrecio);
        TextView LblSabor = (TextView) rootView.findViewById(R.id.LblSabor);
        TextView LblRebozado = (TextView) rootView.findViewById(R.id.LblRebozado);
        TextView LblRelleno = (TextView) rootView.findViewById(R.id.LblRelleno);
        
        txtNombreCachopo.setTypeface(font);
        LblSabor.setTypeface(font);
        LblTamanio.setTypeface(font);
        LblPrecio.setTypeface(font);
        LblRebozado.setTypeface(font);
        LblRelleno.setTypeface(font);
        
        txtSabor.setTypeface(font);
        txtTamanio.setTypeface(font);
        txtPrecio.setTypeface(font);
        txtRebozado.setTypeface(font);
        txtRelleno.setTypeface(font);
        
        rtSaborBar.setRating(cachopoGlobal.getSabor().floatValue());
        rtSaborBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
			
			@Override
			public void onRatingChanged(RatingBar ratingBar, float rating,
					boolean fromUser) {			
				txtSabor.setText(String.valueOf(rating));				
			}
		});
        
        
        rtTamanioBar.setRating(cachopoGlobal.getTamanio().floatValue());
        rtTamanioBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
			
			@Override
			public void onRatingChanged(RatingBar ratingBar, float rating,
					boolean fromUser) {			
				txtTamanio.setText(String.valueOf(rating));				
			}
		});
        rtPrecioBar.setRating(cachopoGlobal.getPrecio().floatValue());
        rtPrecioBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
			
			@Override
			public void onRatingChanged(RatingBar ratingBar, float rating,
					boolean fromUser) {			
				txtPrecio.setText(String.valueOf(rating));				
			}
		});
        rtRebozadoBar.setRating(cachopoGlobal.getRebozado().floatValue());   
        rtRebozadoBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
			
			@Override
			public void onRatingChanged(RatingBar ratingBar, float rating,
					boolean fromUser) {			
				txtRebozado.setText(String.valueOf(rating));				
			}
		});

        rtRellenoBar.setRating(cachopoGlobal.getRelleno().floatValue());
        rtRellenoBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
			
			@Override
			public void onRatingChanged(RatingBar ratingBar, float rating,
					boolean fromUser) {			
				txtRelleno.setText(String.valueOf(rating));				
			}
		});

        txtSabor.setText(cachopoGlobal.getSabor().toString());
        txtTamanio.setText(cachopoGlobal.getTamanio().toString());
        txtRelleno.setText(cachopoGlobal.getRelleno().toString());
        txtPrecio.setText(cachopoGlobal.getPrecio().toString());
        txtRebozado.setText(cachopoGlobal.getRebozado().toString());
        
       
        
	}
    

	@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }
    
	public class threadImgCachopoXEstabl extends AsyncTask <Void, Integer, Boolean> {
	    	
			Constantes cons = new Constantes();
			
	    	String urlFotosXEstb = cons.HOST_SERVICIOWEB_LOCAL+cons.SW_OBTENER_FOTOS_X_ESTAB;
	
	    	
	    	@Override
	    	protected Boolean doInBackground(Void... params) {
	    		
	    	      try{
	    	    	  JSONManager jManager = new JSONManager();
	    	    	 jsonResult = jManager.getJSONfromURL(urlFotosXEstb,null);
	    	     }catch(Exception e){
	    	    	 
	    	     }
	    	      
	    	     return true;
	    	}
	    	
	    	@Override
	    	protected void onProgressUpdate(Integer... values) {
	    	//	 int progreso = values[0].intValue();
	    	//	 pbarProgreso.setProgress(progreso);
	    	}
	    	
	    	@Override
	    	protected void onPreExecute() {
//	    		pbarProgreso.setMax(100);
//	    		pbarProgreso.setProgress(0);
	    	}
	    	
	    	@Override
	    	protected void onPostExecute(Boolean result) {
	    		if(result){
	    			
	    			try {
	    				if(jsonResult != null){
	    					listaFotos=JsonParsers.parseJSONFotos(jsonResult.getJSONArray("fotosCachopo"));
	    					
	    				}
	    				
	    				
	    			} catch (JSONException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
	    			//pbarProgreso.setVisibility(View.INVISIBLE);
	    			Toast.makeText(context, "Carga finalizada!", Toast.LENGTH_SHORT).show();
	    			
	    		}
	    	}
	    	
	    	@Override
	    	protected void onCancelled() {
	    		Toast.makeText(context, "Carga cancelada!", Toast.LENGTH_SHORT).show();
	    	}
	    }
	
	public class threadComentarios extends AsyncTask <Void, Integer, Boolean> {
    	
		Constantes cons = new Constantes();
		ComentarioVO comentario;
    	String urlcomentarios = cons.HOST_SERVICIOWEB+cons.SW_OBTENER_COMENTARIOS;

    	
    	public threadComentarios(ComentarioVO comentarioVO) {
    		comentario=comentarioVO;
		}

		@Override
    	protected Boolean doInBackground(Void... params) {
    		
    	      try{
    	    	  JSONManager jManager = new JSONManager();
    	    	 jsonResult = jManager.getJSONfromURL(urlcomentarios,comentario);
    	     }catch(Exception e){
    	    	 
    	     }
    	      
    	     return true;
    	}
    	
    	@Override
    	protected void onProgressUpdate(Integer... values) {
    	//	 int progreso = values[0].intValue();
    	//	 pbarProgreso.setProgress(progreso);
    	}
    	
    	@Override
    	protected void onPreExecute() {
    		pbarProgresoComentarios.setMax(100);
    		pbarProgresoComentarios.setProgress(0);
    	}
    	
    	@Override
    	protected void onPostExecute(Boolean result) {
    		if(result){
    			
    			try {
    				if(jsonResult != null){
    					listaComentarios=JsonParsers.parseJSONComentarios(jsonResult.getJSONArray("comentarios"));
    					listComentarios.setAdapter(new ListaComentariosBaseAdapter(FragmentDetalleCachopos.context, listaComentarios));
    					
    				}
    				
    				
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			pbarProgresoComentarios.setVisibility(View.GONE);
    			
    		}
    	}
    	
    	@Override
    	protected void onCancelled() {
    		Toast.makeText(context, "Carga cancelada!", Toast.LENGTH_SHORT).show();
    	}
    }
    
    
}
